package org.example.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.Dao.PermissionDao;
import org.example.Dao.RPDao;
import org.example.Dao.RolesDao;
import org.example.Dao.URDao;
import org.example.Pojo.*;
import org.example.Service.RolesService;
import org.example.Utils.UnionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RolesServiceImpl implements RolesService {
    @Resource
    private PermissionDao permissionDao;
    @Resource
    private RolesDao rolesDao;
    @Resource
    private RPDao rpDao;
    @Resource
    private URDao urDao;
    @Override
    public UnionResult addRole(Roles role) {
        if (rolesDao.insert(role) > 0){
            return UnionResult.Success();
        }else{
            return UnionResult.Failure();
        }
    }

    @Override
    public UnionResult removeRole(Roles role) {
        QueryWrapper<RP> rpQueryWrapper = new QueryWrapper<>();
        rpQueryWrapper.eq("role_id",role.getUid());
        if (rpDao.selectCount(rpQueryWrapper) > 0){
            return UnionResult.Failure("该角色下还有权限！");
        }
        QueryWrapper<UR> urQueryWrapper = new QueryWrapper<>();
        urQueryWrapper.eq("role_id",role.getUid());
        if (urDao.selectCount(urQueryWrapper) > 0){
            return UnionResult.Failure("该角色下还有用户！");
        }
        QueryWrapper<Roles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",role.getUid());
        if (rolesDao.delete(queryWrapper) > 0){
            return UnionResult.Success();
        }else{
            return UnionResult.Failure();
        }
    }

    @Override
    public UnionResult updateRole(Roles role) {
        if (rolesDao.updateById(role) > 0){
            return UnionResult.Success();
        }else{
            return UnionResult.Failure();
        }
    }

    @Override
    public UnionResult getRoles() {
        QueryWrapper<Roles> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("uid");
        List<Roles> roles = rolesDao.selectList(queryWrapper);
        return UnionResult.Success("",roles);
    }
}
